
#include <pthread.h>
#include <memory>
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;

#include "Task.hpp"
#include "ringQueue.hpp"
using namespace ringqueue;

#include <unistd.h>
void *productorDemo(void *args)
{
    ringQueue<culculateTask<int>> *rq = static_cast<ringQueue<culculateTask<int>> *>(args);
    while (true)
    { /*生产者生产数据*/
        int left = rand() % 100;
        int right = rand() % 100;
        char oper[5] = {'+','-','*','/','%'};
        culculateTask<int> task(left,right,oper[rand() % 5]);
        rq->push(task);
        cout << "productor: " << pthread_self() << " send a task: " << task.getTaskName() << endl;
    }
}

void *consumerDemo(void *args)
{
    ringQueue<culculateTask<int>> *rq = static_cast<ringQueue<culculateTask<int>> *>(args);
    while (true)
    { /*消费者消费数据*/
        culculateTask<int> task;
        rq->pop(&task);
        cout << "consumer :" << pthread_self() << " get a task: ";
        task();/*该任务内部已经打印了计算结果*/
        sleep(1);/*消费者消费的慢一些*/
    }
}

int main()
{
    srand((unsigned int)time(nullptr));
    vector<pthread_t> vec;
    /*环形队列用来存储用于整形计算的任务
     *calculate打错了，打成了culculate，读者自己注意*/
    ringQueue<culculateTask<int>> *rq = new ringQueue<culculateTask<int>>();

    for (int i = 0; i < 4; i++)
    {
        pthread_t productor;
        pthread_create(&productor, nullptr, productorDemo, rq);
        vec.push_back(productor);
    }

    for (int i = 0; i < 4; i++)
    {
        pthread_t consumer;
        pthread_create(&consumer, nullptr, consumerDemo, rq);
        vec.push_back(consumer);
    }

    for (auto &e : vec)
    {
        pthread_join(e, nullptr);
    }
    return 0;
}